package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.user.prop.WXProperties;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author luoyin
 * @Date 18:59 2022/10/4
 **/
@Controller
@RequestMapping("/user/wx")
public class WXLoginController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WXProperties wxProperties;

    @ResponseBody
    @GetMapping("/param")
    public R getLoginParam() throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("appid",wxProperties.getAppid());
        map.put("scope","snsapi_login");
        map.put("secret",wxProperties.getSecret());
        String redirectUri = URLEncoder.encode(wxProperties.getRedirectUri(), "UTF-8");
        map.put("redirectUri", redirectUri);
        map.put("state",System.currentTimeMillis()+"");
        return R.ok().data(map);
    }

    @GetMapping("/callback")
    public String callback(String code , String state) throws Exception {

        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String format = String.format(sb.toString(),wxProperties.getAppid(),wxProperties.getSecret(),code );
        //get访问,获取微信和第三方的唯一凭证
        String getAccessToken = HttpClientUtils.get(format);
        JSONObject jsonObject = JSONObject.parseObject(getAccessToken);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //get访问 ,获取账户用户信息
        String getUserInfo = HttpClientUtils.get("https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid);
        JSONObject userInfo = JSONObject.parseObject(getUserInfo);
        String nickname = userInfo.getString("nickname");

        Map<String,String> map = userInfoService.WXlogin(openid,nickname);

        return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+ URLEncoder.encode(map.get("name"), "UTF-8");
    }
}
